<?php

namespace App\Http\Middleware;
use Closure;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Redis;

class UserToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->input('token');
        if (config('app.debug') == true && empty($token)) {
            return $next($request);
        }
        //检测用户是否传token(必须登录)
        if (empty($token)) {
            return Controller::response(null,-99,'尚未登陆！');
        }
        try {
            $decrypted = decrypt($token);
        } catch (DecryptException $e) {
            return Controller::response(null,-99,'尚未登陆！');
        }
        if (empty($decrypted) || empty($decrypted['timestamp']) || empty($decrypted['user_id'])|| empty($decrypted['ip'])) {
            return Controller::response(null,-99,'尚未登陆！');
        }
        if (time()-$decrypted['timestamp'] > 3600*24*365) {
            return Controller::response(null,-99,'用户登陆状态过期');
        }
        if ($request->ip() !== $decrypted['ip']) {
            return Controller::response(null,-99,'您的账号已在别处登陆，如不是本人操作请尽快修改密码');
        }
        $user_id = $decrypted['user_id'];
        $token_cache  = Redis::get('UserTokenString::'.$user_id);
        if (empty($token_cache)) {
            return Controller::response(null,-99,'用户登陆状态过期');
        }
        if ($token_cache !== $token) {
            return Controller::response(['user_token'=>$token_cache,'token'=>$token],-99,'您的账号已在别处登陆，如不是本人操作请尽快修改密码');
        }
        $request->merge(['user_id' => $user_id]);
        return $next($request);
    }
}
